// stores/dashboard.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import dashboardApi from '@/api/dashboard'

export const useDashboardStore = defineStore('dashboard', () => {
    // 状态
    const loading = ref(false)
    const dashboardData = ref(null)
    const refreshing = ref(false)

    // 获取仪表盘数据
    const fetchDashboardData = async () => {
        try {
            loading.value = true
            const response = await dashboardApi.getDashboardData()
            dashboardData.value = response.data
        } catch (error) {
            console.error('获取仪表盘数据失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    // 获取指定天数的数据
    const fetchDashboardDataByDays = async (days) => {
        try {
            loading.value = true
            const response = await dashboardApi.getDashboardDataByDays(days)
            dashboardData.value = response.data
        } catch (error) {
            console.error('获取仪表盘数据失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    // 刷新统计数据
    const refreshStatistics = async () => {
        try {
            refreshing.value = true
            await dashboardApi.refreshStatisticsCache()
            await fetchDashboardData()
        } catch (error) {
            console.error('刷新统计数据失败:', error)
            throw error
        } finally {
            refreshing.value = false
        }
    }

    return {
        // 状态
        loading,
        refreshing,
        dashboardData,

        // 方法
        fetchDashboardData,
        fetchDashboardDataByDays,
        refreshStatistics
    }
})